<template>
  <div class="container">
    <el-form
      class="login-box"
      :model="form"
      status-icon
      :rules="rules"
      ref="ruleForm"
      @keydown.enter.native="submit('ruleForm')"
    >
      <div class="form-title">小猿管理系统</div>
      <el-form-item prop="username">
        <el-input
          prefix-icon="el-icon-user"
          v-model="form.username"
          placeholder="请输入账号"
        ></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          prefix-icon="el-icon-lock"
          type="password"
          v-model="form.password"
          placeholder="请输入密码"
        ></el-input>
      </el-form-item>
      <el-form-item prop="code">
        <el-row type="flex" justify="space-between">
          <el-col :span="16">
            <el-input
              prefix-icon="el-icon-copy-document"
              v-model.number="form.code"
              placeholder="请输入验证码"
            ></el-input>
          </el-col>
          <el-col :span="7">
            <div class="code-img" ref="codeImg" @click="drawCode"></div>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item prop="remember">
        <el-row type="flex" justify="space-between">
          <el-col :span="5">
            <el-checkbox v-model="form.remember">记住密码</el-checkbox>
          </el-col>
          <el-col :span="5">
            <el-button type="text">忘记密码？</el-button>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item>
        <el-button
          class="login"
          type="primary"
          :loading="logined"
          @click="submit('ruleForm')"
        >
          {{ logined ? "正在登录..." : "登录" }}
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "LittleApeFrameworkLogin",

  data() {
    var username = (rule, value, callback) => {
      if (value.length < 5) {
        callback(new Error("请输入正确的账号"));
      } else {
        callback();
      }
    };
    var password = (rule, value, callback) => {
      let regex = /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[^\w\s]).*$/;
      if (value.length < 6) {
        callback(new Error("密码至少6位数"));
      } else if (!regex.test(value)) {
        callback(new Error("密码至少要同时包含字母、数字、特殊字符"));
      } else {
        callback();
      }
    };
    var code = (rule, value, callback) => {
      if (value.length != 4) {
        callback(new Error("验证码是4位数"));
      } else {
        callback();
      }
    };
    return {
      logined: false,
      code: "",
      form: {
        username: "",
        password: "",
        code: "",
        remember: false,
      },
      rules: {
        username: [{ validator: username, trigger: "change" }],
        password: [{ validator: password, trigger: "change" }],
        code: [{ validator: code, trigger: "change" }],
      },
    };
  },

  mounted() {
    this.drawCode();
  },

  methods: {
    submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.login();
        } else {
          return false;
        }
      });
    },
    login() {
      let form = this.form;
      if (this.code.toLowerCase() === form.code.toLowerCase()) {
        this.logined = true
      } else {
        this.$message.error("验证码错误");
        this.drawCode();
      }
    },
    drawCode() {
      let ele = this.$refs.codeImg;
      let w = ele.offsetWidth;
      let h = ele.offsetHeight;
      // 先清空旧的 Canvas
      const old = ele.querySelector("canvas");
      if (old) {
        old.remove();
      }
      // 创建新的 Canvas 元素
      const canvas = document.createElement("canvas");
      canvas.width = w;
      canvas.height = h;
      ele.appendChild(canvas);
      if (canvas.getContext) {
        const ctx = canvas.getContext("2d");
        // 生成随机的验证码
        const chars =
          "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        let code = "";
        for (let i = 0; i < 4; i++) {
          code += chars.charAt(Math.floor(Math.random() * chars.length));
        }
        this.code = code;
        // 生成随机背景色
        let bgColor = "#" + Math.floor(Math.random() * 16777215).toString(16);
        ctx.fillStyle = bgColor;
        ctx.fillRect(0, 0, w, h);
        // 生成随机线条
        for (let i = 0; i < 4; i++) {
          const startX = Math.random() * w;
          const startY = Math.random() * h;
          const endX = Math.random() * w;
          const endY = Math.random() * h;
          ctx.strokeStyle =
            "#" + Math.floor(Math.random() * 16777215).toString(16);
          ctx.beginPath();
          ctx.moveTo(startX, startY);
          ctx.lineTo(endX, endY);
          ctx.stroke();
        }
        // 设置字体样式
        ctx.font = "30px 微软雅黑";
        ctx.fillStyle = "#" + Math.floor(Math.random() * 16777215).toString(16);

        // 计算居中位置并绘制验证码
        const textWidth = ctx.measureText(code).width;
        const textHeight = ctx.measureText(code).height;
        const x = (w - textWidth) / 2;
        const y = (h + 20) / 2;
        ctx.fillText(code, x, y);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  min-height: 100vh;
  background-image: url("@/assets/background.jpg");
  background-size: cover;
  background-position: center;
  display: flex;
  align-items: center;
  justify-content: center;

  .login-box {
    padding: 20px;
    width: 400px;
    height: fit-content;
    border-radius: 10px;
    background: rgba($color: #fff, $alpha: 0.5);
    backdrop-filter: blur(10px);
    box-shadow: 0 0 10px 5px rgba($color: #313131, $alpha: 0.5);
    box-sizing: border-box;
    user-select: none;

    .form-title {
      padding-bottom: 20px;
      width: 100%;
      text-align: center;
      font-size: 20px;
      color: #313131;
      font-weight: bold;
    }

    .code-img {
      width: 100%;
      height: 40px;
      background: rgba($color: #000000, $alpha: 0.1);
      border-radius: 5px;
      overflow: hidden;
      cursor: pointer;
    }

    .login {
      width: 100%;
    }
  }
}
</style>
